/**
 * 
 */
package core;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.Scanner;

import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.sites.ContentQuery;
import com.google.gdata.client.sites.SitesService;
import com.google.gdata.data.XhtmlTextConstruct;
import com.google.gdata.data.sites.ActivityFeed;
import com.google.gdata.data.sites.BaseActivityEntry;
import com.google.gdata.data.sites.BaseContentEntry;
import com.google.gdata.data.sites.ContentFeed;
import com.google.gdata.data.sites.ListItemEntry;
import com.google.gdata.data.sites.ListPageEntry;
import com.google.gdata.data.sites.SiteEntry;
import com.google.gdata.data.sites.SiteFeed;
import com.google.gdata.data.sites.SitesLink;
import com.google.gdata.data.spreadsheet.Field;
import com.google.gdata.model.atom.Link;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;

/**
 * @author Tomasz
 * 
 */
public class ListGenerator {

	private static SitesService client;
	private static ContentFeed contentFeed;
	private static String domain;
	private static String siteName;

	/**
	 * @param args
	 * @throws ServiceException
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException, ServiceException {
		Properties configFile = new Properties();
		configFile.load(ListGenerator.class.getClassLoader()
				.getResourceAsStream("config.properties"));

		client = new SitesService(configFile.getProperty("appName"));
		client.setUserCredentials(configFile.getProperty("login"),
				configFile.getProperty("password"));

		domain = configFile.getProperty("domain");
		siteName = configFile.getProperty("siteName");

		// ContentQuery query = new ContentQuery(new
		// URL(buildContentFeedUrl()));
		// query.setPath("/jobslist");
		contentFeed = client.getFeed(new URL(buildContentFeedUrl()),
				ContentFeed.class);
		ListPageEntry listPage;/// = contentFeed.getEntries(ListPageEntry.class).get(0); // Update first list page found

		// Update HTML content
		XmlBlob xml = new XmlBlob();
		xml.setBlob("<p>Updated HTML Content</p>");
		//listPage.setContent(new XhtmlTextConstruct(xml));

		//ListPageEntry updatedEntry = listPage.update();

		deleteListItemEntries(contentFeed);

		addListItems(contentFeed.getEntries(ListPageEntry.class).get(0));
	}

	private void setContentBlob(BaseContentEntry<?> entry, String pageContent) {
		XmlBlob xml = new XmlBlob();
		xml.setBlob(pageContent);
		entry.setContent(new XhtmlTextConstruct(xml));
	}

	public static void addListItems(ListPageEntry parentPage)
			throws MalformedURLException, IOException, ServiceException {
		File file = new File("data/jobs.txt");
		Scanner scanner = new Scanner(file);
		scanner.useDelimiter("[\t\n]");
		while (scanner.hasNext()) {
			String date = scanner.next();
			String location = scanner.next();
			String description = scanner.next();
			scanner.next();
			String abs_link = scanner.next();
			addListItemEntry(parentPage, date, location, description, abs_link);
		}
		scanner.close();
	}
	
	private static String convertDate(String date){
		String[] arr = date.split("/");
		
		return arr[2] + "-" + arr[1] + "-" + arr[0];
		
	}

	public static ListItemEntry addListItemEntry(ListPageEntry parentPage,
			String date, String location, String description, String abs_link)
			throws MalformedURLException, IOException, ServiceException {

		ListItemEntry entry = new ListItemEntry();
		entry.getFields().add(0, new Field());
		entry.getFields().add(1, new Field());
		entry.getFields().add(2, new Field());
		entry.getFields().add(3, new Field());
		entry.getFields().get(0).setName("Date");
		entry.getFields().get(1).setName("Location");
		entry.getFields().get(2).setName("Job Description");
		entry.getFields().get(3).setName("Details");
		entry.getFields().get(0).setValue(convertDate(date));
		entry.getFields().get(1).setValue(location);
		entry.getFields().get(2).setValue(description);
		entry.getFields().get(3)
				.setValue("<a href='" + abs_link + "'>Details</a>");

		entry.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentPage
				.getSelfLink().getHref());

		return client.insert(new URL(buildContentFeedUrl()), entry);
	}

	public static String buildContentFeedUrl() {
		return "https://sites.google.com/feeds/content/" + domain + "/"
				+ siteName + "/";
	}

	public static String getSiteFeedUrl() {
		String domain = "gjobssearch.com"; // OR if the Site is hosted on Google
											// Apps, your domain (e.g.
											// example.com)
		return "https://sites.google.com/feeds/site/" + domain + "/";
	}

	public static void getSiteFeed() throws IOException, ServiceException {
		SiteFeed siteFeed = client.getFeed(new URL(getSiteFeedUrl()),
				SiteFeed.class);
		for (SiteEntry entry : siteFeed.getEntries()) {
			System.out.println("title: " + entry.getTitle().getPlainText());
			System.out.println("site name: " + entry.getSiteName().getValue());
			System.out.println("theme: " + entry.getTheme().getValue());
			System.out.println("");
		}
	}

	public static String buildActivityFeedUrl() {
		return "https://sites.google.com/feeds/activity/" + domain + "/"
				+ siteName + "/";
	}

	public static void getActivityFeed() throws IOException, ServiceException {
		ActivityFeed activityFeed = client.getFeed(new URL(
				buildActivityFeedUrl()), ActivityFeed.class);
		for (BaseActivityEntry<?> entry : activityFeed.getEntries()) {
			System.out.println(entry.getSummary().getPlainText());
			System.out.println(" revisions link: "
					+ entry.getRevisionLink().getHref());
		}
	}

	public static void deleteListItemEntries(ContentFeed contentFeed)
			throws IOException, ServiceException {

		while (true) {

			contentFeed = client.getFeed(new URL(buildContentFeedUrl()),
					ContentFeed.class);
			if (contentFeed.getEntries(ListItemEntry.class).size() == 0)
				return;
			System.out.println(contentFeed.getEntries(ListItemEntry.class)
					.size());

			// contentFeed.getNextLink().
			for (ListItemEntry entry : contentFeed
					.getEntries(ListItemEntry.class)) {
				entry.delete();
			}

		}

	}

	public static String getContentBlob(BaseContentEntry<?> entry) {
		return ((XhtmlTextConstruct) entry.getTextContent().getContent())
				.getXhtml().getBlob();
	}

	// Extracts an entry's numeric ID.
	private static String getEntryId(String selfLink) {
		return selfLink.substring(selfLink.lastIndexOf("/") + 1);
	}

}
